package com.nbrc.web;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.engine.impl.interceptor.Command;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.nbrc.helper.AjaxMessage;
import com.nbrc.helper.Pagenation;
import com.nbrc.jsonmodel.MyProcess;
import com.nbrc.jsonmodel.MyTask;
import com.nbrc.model.Myleave;
import com.nbrc.model.Role;
import com.nbrc.model.User;
import com.nbrc.service.CommonService;
import com.nbrc.uil.HistoryProcessInstanceDiagramCmd;

@Controller
public class CommonController {
	@Autowired
	@Qualifier("commonService")
	CommonService cs;

	/*
	 * @Autowired private TaskService taskService;
	 * 
	 * @Autowired private HistoryService historyService;
	 */

	@RequestMapping(value = { "", "/","/login"})
	public String webinit(Model model) {
		return "login";
	}

	/*
	 * private Model index(HttpSession session,Model m) { User user = (User)
	 * session.getAttribute("user"); Role role =
	 * (Role)session.getAttribute("role"); List<Task> taskAssignee =
	 * taskService.createTaskQuery() .taskAssignee(user.getId()).list();//
	 * 获取这个用户要出来的任务 List<Task> taskCandidateUser = taskService.createTaskQuery()
	 * .taskCandidateUser(user.getId()).list();// 获取这个用户所在组的可以认领的任务 List<Task>
	 * taskCandidateGroup = taskService.createTaskQuery()
	 * .taskCandidateGroup(role.getId()).list();// 获取这个用户要认领的任务
	 * m.addAttribute("taskAssignee", taskAssignee);
	 * m.addAttribute("taskCandidateUser", taskCandidateUser);
	 * m.addAttribute("taskCandidateGroup", taskCandidateGroup);
	 * List<HistoricProcessInstance> started = historyService
	 * .createHistoricProcessInstanceQuery()
	 * .startedBy(user.getId()).list();//获取这个用户提交的申请
	 * List<HistoricProcessInstance> finished = historyService
	 * .createHistoricProcessInstanceQuery().finished()
	 * .startedBy(user.getId()).list();//获取这个用户提交的已经结束申请
	 * List<HistoricProcessInstance> unfinished = historyService
	 * .createHistoricProcessInstanceQuery().unfinished()
	 * .startedBy(user.getId()).list();//获取这个用户提交的还在审批申请
	 * m.addAttribute("started", started); m.addAttribute("finished", finished);
	 * m.addAttribute("unfinished", unfinished); m.addAttribute("unfinished",
	 * unfinished); return m; }
	 */
	/**
	 * 登陆action
	 * 
	 * @param username
	 *            用户名
	 * @param userpassword
	 *            密码
	 * @param SecurityCode
	 *            验证码
	 * @param session
	 * @param m
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String loginPOST(String username, String userpassword,
			String SecurityCode, HttpSession session, Model m) {
		String rand = session.getAttribute("rand").toString();
		System.out.println(username + " " + userpassword + " " + SecurityCode
				+ " " + rand);
		if (rand.equalsIgnoreCase(SecurityCode)) {
			User user = cs.login(username, userpassword);
			if (user != null) {
				session.setAttribute("user", user);
				Role role = user.getRole();
				session.setAttribute("role", role);
				session.setAttribute("menu", role.getMenus());
				// m = index(session,m);
				return "/index";
			} else {
				m.addAttribute("message", "账号或者密码错误");
			}
		} else {
			m.addAttribute("message", "验证码错误");
		}

		return "redirect:/";
	}

	/*
	 * @RequestMapping(value = "/claim") public String claim(String id,
	 * HttpSession session, Model m) { User user = (User)
	 * session.getAttribute("user"); taskService.claim(id,user.getId()); m =
	 * index(session,m); return "index";
	 * 
	 * }
	 * 
	 * @RequestMapping(value = "/completeTrue") public String
	 * completeTrue(String id, HttpSession session, Model m,String varString) {
	 * Map<String, Object> variables = new HashMap<String, Object>(); Role role
	 * = (Role)session.getAttribute("role");
	 * if(role.getId().equals("1f0e5af8-f09a-4425-8fa5-96bbc89cfb80")){
	 * variables.put("zrComment", "同意"); }else
	 * if(role.getId().equals("7b2290f1-d929-4442-8624-99d7852b024f")){
	 * variables.put("bzComment", "同意"); } taskService.complete(id,variables);
	 * //m = index(session,m); return "index";
	 * 
	 * }
	 * 
	 * @RequestMapping(value = "/completeFalse") public String
	 * completeFalse(String id, HttpSession session, Model m) { Map<String,
	 * Object> variables = new HashMap<String, Object>(); Role role =
	 * (Role)session.getAttribute("role");
	 * if(role.getId().equals("1f0e5af8-f09a-4425-8fa5-96bbc89cfb80")){
	 * variables.put("zrComment", "不同意"); }else
	 * if(role.getId().equals("7b2290f1-d929-4442-8624-99d7852b024f")){
	 * variables.put("bzComment", "不同意"); } taskService.complete(id,variables);
	 * //m = index(session,m); return "index";
	 * 
	 * }
	 */
	@RequestMapping(value = "/completeFalse")
	public String completeFalse(String id, HttpSession session, Model m) {
		Map<String, Object> variables = new HashMap<String, Object>();
		Role role = (Role) session.getAttribute("role");
		if (role.getId().equals("1f0e5af8-f09a-4425-8fa5-96bbc89cfb80")) {
			variables.put("zrComment", "不同意");
		} else if (role.getId().equals("7b2290f1-d929-4442-8624-99d7852b024f")) {
			variables.put("bzComment", "不同意");
		}
		cs.complete(id, variables);
		return "redirect:/alltaskassignee";

	}

	@RequestMapping(value = "/completeTrue")
	public String completeTrue(String id, HttpSession session, Model m,
			String varString) {
		Map<String, Object> variables = new HashMap<String, Object>();
		Role role = (Role) session.getAttribute("role");
		if (role.getId().equals("1f0e5af8-f09a-4425-8fa5-96bbc89cfb80")) {
			variables.put("zrComment", "同意");
		} else if (role.getId().equals("7b2290f1-d929-4442-8624-99d7852b024f")) {
			variables.put("bzComment", "同意");
		}
		cs.complete(id, variables);
		return "redirect:/alltaskassignee";
	}

	@RequestMapping(value = "/claimtaskvandidategroup")
	public String claimtaskvandidategroup(String id, HttpSession session,
			Model m, String varString) {
		User user = (User) session.getAttribute("user");
		cs.claim(id, user);
		return "redirect:/taskvandidategroup";
	}

	@RequestMapping(value = "/claimtaskvandidateuser")
	public String claimtaskvandidateuser(String id, HttpSession session,
			Model m, String varString) {
		User user = (User) session.getAttribute("user");
		cs.claim(id, user);
		return "redirect:/taskvandidateuser";
	}

	@RequestMapping(value = "/addMyLeave", method = RequestMethod.POST)
	@ResponseBody
	public AjaxMessage addLeavePOST(Myleave leave, HttpSession session, Model m) {
		User user = (User) session.getAttribute("user");
		Role role = (Role) session.getAttribute("role");
		AjaxMessage am = new AjaxMessage();
		if (cs.saveLeave(leave, user, role)) {
			am.setMessage("成功");
			am.setSuccess(true);
		} else {
			am.setMessage("失败");
			am.setSuccess(false);
		}
		return am;

	}

	@RequestMapping(value = "/finished", method = RequestMethod.GET)
	public String finishedGET(HttpSession session, Model m) {
		return "finished";

	}

	@RequestMapping(value = "/getAllFinished", method = RequestMethod.POST)
	@ResponseBody
	public Pagenation<MyProcess> getAllFinishedPOST(HttpSession session,
			Model m, @RequestParam(required = false) String key,
			@RequestParam(defaultValue = "1", required = false) int page,
			@RequestParam(defaultValue = "10", required = false) int rows) {
		User user = (User) session.getAttribute("user");
		Pagenation<MyProcess> pp = cs.allFinished(user, page, rows);
		return pp;
	}

	@RequestMapping(value = "/getOneMyLeave", method = RequestMethod.POST)
	@ResponseBody
	public Myleave getOneMyLeavePOST(HttpSession session, Model m, String id) {
		return cs.getOneMyLeave(id);
	}

	@RequestMapping(value = "/alltaskassignee", method = RequestMethod.GET)
	public String alltaskassigneeGET(HttpSession session, Model m) {

		return "alltaskassignee";

	}

	@RequestMapping(value = "/getAlltaskassignee", method = RequestMethod.POST)
	@ResponseBody
	public Pagenation<MyTask> getAlltaskassigneePOST(HttpSession session,
			Model m, @RequestParam(required = false) String key,
			@RequestParam(defaultValue = "1", required = false) int page,
			@RequestParam(defaultValue = "10", required = false) int rows) {
		User user = (User) session.getAttribute("user");
		return cs.getAlltaskassignee(user, key, page, rows);
	}

	@RequestMapping(value = "/taskvandidategroup", method = RequestMethod.GET)
	public String taskCandidateGroupGET(HttpSession session, Model m) {

		return "taskvandidategroup";

	}

	@RequestMapping(value = "/gettaskvandidategroup", method = RequestMethod.POST)
	@ResponseBody
	public Pagenation<MyTask> getAlltaskCandidateGroupPOST(HttpSession session,
			Model m, @RequestParam(required = false) String key,
			@RequestParam(defaultValue = "1", required = false) int page,
			@RequestParam(defaultValue = "10", required = false) int rows) {
		Role role = (Role) session.getAttribute("role");
		return cs.getAlltaskCandidateGroup(role, key, page, rows);
	}

	@RequestMapping(value = "/modifymyleave", method = RequestMethod.GET)
	public String modifymyleaveGET(HttpSession session, Model m) {

		return "modifymyleave";

	}

	@RequestMapping(value = "/getmodifymyleave", method = RequestMethod.POST)
	@ResponseBody
	public Pagenation<MyTask> getmodifymyleavePOST(HttpSession session,
			Model m, @RequestParam(required = false) String key,
			@RequestParam(defaultValue = "1", required = false) int page,
			@RequestParam(defaultValue = "10", required = false) int rows) {
		User user = (User) session.getAttribute("user");
		return cs.getAlltaskassignee(user, key, page, rows);
	}

	@RequestMapping(value = "/onemodifymyleave", method = RequestMethod.POST)
	@ResponseBody
	public AjaxMessage onemodifymyleavePOST(Myleave leave, HttpSession session,
			Model m, String taskid) {
		AjaxMessage am = new AjaxMessage();
		if (cs.oneModifyMyleave(leave, taskid)) {
			am.setMessage("成功");
			am.setSuccess(true);
		} else {
			am.setMessage("失败");
			am.setSuccess(false);
		}

		return am;

	}

	@RequestMapping(value = "/img", method = RequestMethod.POST)
	public String img() {
		return "graphHistoryProcessInstance";
	}

	@RequestMapping(value = "/graphHistoryProcessInstance")
	public void graphHistoryProcessInstance(HttpServletResponse response,
			String processInstanceId) {
		if(processInstanceId!=null&&!StringUtils.isEmpty(processInstanceId)){
			try {
				InputStream is = cs.graphHistoryProcessInstance(processInstanceId);
				response.setContentType("image/png");
				int len = 0;
				byte[] b = new byte[1024];
				while ((len = is.read(b, 0, 1024)) != -1) {
					response.getOutputStream().write(b, 0, len);
					
				}
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				System.out.println("sssssssss e="+e.getMessage());
			}
		}else{
			System.out.println("sssssssss");
		}
		
	}
	@RequestMapping(value = "/systemGraphHistoryProcessInstance")
	public void systemGraphHistoryProcessInstance(HttpServletResponse response,
			String processInstanceId) {
		if(processInstanceId!=null&&!StringUtils.isEmpty(processInstanceId)){
			try {
				InputStream is = cs.systemGraphHistoryProcessInstance(processInstanceId);
				response.setContentType("image/png");
				int len = 0;
				byte[] b = new byte[1024];
				while ((len = is.read(b, 0, 1024)) != -1) {
					response.getOutputStream().write(b, 0, len);
					
				}
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				System.out.println("sssssssss e="+e.getMessage());
			}
		}else{
			System.out.println("sssssssss");
		}
		
	}

}
